package model

import (
	"gorm.io/gorm"
	"post/handler/response"
)

type Post struct {
	gorm.Model
	UserId    int    `gorm:"type:int" json:"userId"`
	Content   string `gorm:"type:varchar(100)" json:"content"`
	PostImage string `gorm:"type:varchar(255)" json:"postImage"`
	VisRange  string `gorm:"type:varchar(30);default:public" json:"visRange"`
	Count     int    `gorm:"type:int;default:0" json:"count"`
}

func (p *Post) AddPost(db *gorm.DB) error {
	return db.Create(&p).Error
}
func (p *Post) GetPostList(db *gorm.DB, userId int, page int, size int) (list []response.PostList, err error) {
	offset := (page - 1) * size
	err = db.Model(&p).
		Select("users.username,avatar_url,posts.content,posts.post_image").
		Joins("LEFT JOIN users ON users.id = posts.user_id").
		Where("posts.user_id in (SELECT friends.friend_id FROM friends WHERE friends.user_id = ?)", userId).
		Offset(offset).Limit(size).Find(&list).Error
	return
}
func (p *Post) GetMyPost(db *gorm.DB, userId int) (list []response.PostList, err error) {
	err = db.Model(&p).
		Select("users.username,avatar_url,posts.content,posts.post_image").
		Joins("LEFT JOIN users ON users.id = posts.user_id").
		Where("posts.user_id = ?", userId).
		Order("posts.created_at desc,posts.count desc").Find(&list).Error
	return
}
func (p *Post) GetPost(db *gorm.DB, postId int) error {
	err := db.Model(&p).Where("posts.id = ?", postId).First(&p).Error
	return err
}
func (p *Post) DelPost(db *gorm.DB, postId int) error {
	err := db.Delete(&p, postId).Error
	return err
}
